
import * as PIXI from 'pixi.js';

import {throttle} from 'common/utils';
import Text from 'components/text';
import Image from 'components/image';
import injectStore from 'components/injectStore';
const { Container } = PIXI;

@injectStore
export default class ShakeOctopusModal {
  constructor({parent, store, onGetItem, ...props}) {

    const {height, box, top, width} = props;
    this.onGetItem = onGetItem;
    this.store = store;
    this.parent = parent;
    this.container = new Container();

    let img = new Image({src: box.src, height: 250, top: 200, isAdapt: true});
    img.x = (width - img.width) / 2;

    let playIcon = new Image({src: box.playIcon, width: 100, height: 100, left: 150, top: 520});

    let useText = new Text({value: box.playTexts, top: 560, fontSize: 28});
    useText.x = (width - useText.width) / 2 + 30;

    this.container.addChild(img);
    this.container.addChild(playIcon);
    this.container.addChild(useText);

    this.container.y = top;
    this.container.x = (window.CFG.view.width - width) / 2;

    this.parent.notHidden = true;
    window.addEventListener('deviceorientation', (e) => {
      this.deviceOrientation(e, () => {
        if (!this.hasplay) {
          this.hasplay = true;
          this.parent.notHidden = false;
          onGetItem();
          this.parent.container.removeChild(this.container);
          const goods = this.store.items.filter(item => JSON.stringify(box.getItems).indexOf(item.key) > -1)[0];
          this.parent._renderContent(goods, onGetItem, true);
        }
      });
    });
  }

  deviceOrientation = (e, onEnd) => {
    throttle(() => {
      const angle = this.gamma ? e.gamma - this.gamma : e.gamma;
      if (
        ((angle < 0 && this.lastAngle > 0) || (angle > 0 && this.lastAngle < 0))
        && (Math.abs(Math.abs(angle) - Math.abs(this.lastAngle)) > 20)
      ) {
        onEnd();

        window.removeEventListener('deviceorientation', this.deviceOrientation);
        delete this.gamma;
        delete this.lastAngle;
      } else {
        this.gamma = e.gamma;
        this.lastAngle = angle;
      }
    }, 200);
  };
}
